<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <title>可编辑网页编辑器</title>
  <style>
    /* 基础样式 */
    body {
      padding: 20px;
      font-family: sans-serif;
      max-width: 800px;
      margin: 0 auto;
    }
   .editable-container {
      border: 2px dashed #ccc;
      padding: 20px;
      min-height: 300px;
      margin-top: 10px;
    }
    /* 可编辑元素样式 */
   .editable-item {
      padding: 15px;
      margin: 10px 0;
      background: #f9f9f9;
      border: 1px solid #eee;
      cursor: grab;
      user-select: none;
      position: relative;
      contenteditable: true;
      transition: all 0.2s ease;
    }
   .editable-item.dragging {
      opacity: 0.7;
      cursor: grabbing;
      background: #e8f4fd;
      transform: scale(1.01);
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
      /* 拖拽时脱离文档流，避免影响其他元素位置计算 */
      position: absolute;
      width: calc(100% - 60px);
      z-index: 100;
    }
    /* 样式面板 */
   .style-panel {
      position: absolute;
      background: white;
      border: 1px solid #ddd;
      padding: 15px;
      box-shadow: 0 3px 15px rgba(0,0,0,0.15);
      z-index: 1000;
      display: none;
      border-radius: 6px;
      width: 220px;
    }
   .style-panel.active {
      display: block;
      animation: fadeIn 0.2s ease;
    }
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(-5px); }
      to { opacity: 1; transform: translateY(0); }
    }
   .style-panel input, select {
      margin: 8px 0;
      width: 100%;
      padding: 6px;
      box-sizing: border-box;
      border: 1px solid #ddd;
      border-radius: 4px;
    }
   .style-panel button {
      margin-top: 10px;
      padding: 6px 12px;
      margin-right: 8px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
   .style-panel button:first-of-type {
      background: #4CAF50;
      color: white;
    }
   .style-panel button:last-of-type {
      background: #f1f1f1;
    }
    /* 排序提示线 */
   .sort-line {
      height: 3px;
      background: #2196F3;
      margin: 10px 0;
      opacity: 0;
      transition: opacity 0.2s ease;
    }
   .sort-line.active {
      opacity: 1;
    }
    /* 操作提示 */
   .instructions {
      color: #666;
      font-size: 14px;
      margin-bottom: 15px;
    }
    /* 调试区域样式 */
   .debug-area {
      margin-top: 30px;
      padding: 15px;
      background: #f5f5f5;
      border-radius: 6px;
    }
   .debug-area h4 {
      margin-top: 0;
      color: #555;
    }
   .html-preview {
      font-family: monospace;
      font-size: 12px;
      white-space: pre-wrap;
      word-wrap: break-word;
      color: #333;
      max-height: 200px;
      overflow-y: auto;
      border: 1px solid #ddd;
      padding: 10px;
      background: white;
      border-radius: 4px;
    }
  </style>
</head>
<body>
  <h3>未来之窗-可编辑网页编辑器</h3>
  <p class="instructions">
    操作提示：点击元素弹出样式面板，按住元素可上下拖拽调整顺序（实时更新HTML结构），直接点击文本可编辑内容
  </p>
  
  <!-- 可编辑容器 -->
  <div class="editable-container" id="editContainer">
    <div class="editable-item">元素 1：点击我打开样式设置面板</div>
    <div class="editable-item">元素 2：拖动我可以调整位置</div>
    <div class="editable-item">元素 3：点击文本可以直接修改内容</div>
    <div class="editable-item">元素 4：支持触摸设备操作</div>

	  <div class="editable-item">元素 555：支持触摸设备操作</div>
  </div>

  <!-- 样式设置面板 -->
  <div class="style-panel" id="stylePanel">
    <select id="fontSize">
      <option value="12px">12px</option>
      <option value="14px" selected>14px</option>
      <option value="16px">16px</option>
      <option value="18px">18px</option>
      <option value="20px">20px</option>
      <option value="24px">24px</option>
      <option value="28px">28px</option>
    </select>
    
    <input type="color" id="fontColor" value="#333333">
    
    <select id="fontFamily">
      <option value="sans-serif" selected>默认字体</option>
      <option value="serif">衬线字体</option>
      <option value="monospace">等宽字体</option>
      <option value="'Microsoft YaHei'">微软雅黑</option>
      <option value="'SimSun'">宋体</option>
    </select>
    
    <input type="text" id="width" placeholder="宽度(px或%)" value="100%">
    <input type="number" id="height" placeholder="高度(px)" value="">
    
    <button onclick="applyStyle()">应用</button>
    <button onclick="closePanel()">关闭</button>
  </div>

  <!-- 调试区域：展示当前HTML结构 -->
  <div class="debug-area">
    <h4>当前HTML结构（实时更新）：</h4>
    <div class="html-preview" id="htmlPreview"></div>
  </div>

  <script>
    // 全局变量
    let currentItem = null;
    let isDragging = false;
    let startY = 0;
    let startX = 0;
    let initialPosition = { top: 0, left: 0 };
    let originalIndex = -1;
    const container = document.getElementById('editContainer');
    const panel = document.getElementById('stylePanel');
    const htmlPreview = document.getElementById('htmlPreview');

    // 初始化
    function init() {
      // 为所有可编辑元素绑定事件
      document.querySelectorAll('.editable-item').forEach(bindItemEvents);
      
      // 点击空白处关闭面板
      document.addEventListener('click', (e) => {
        if (!panel.contains(e.target) &&!e.target.closest('.editable-item')) {
          closePanel();
        }
      });

      // 初始更新HTML预览
      updateHtmlPreview();
    }

    // 为元素绑定事件
    function bindItemEvents(item) {
      // 点击显示样式面板
      item.addEventListener('click', (e) => {
        // 如果是拖拽过程中点击，不触发面板
        if (isDragging) return;
        
        e.stopPropagation();
        currentItem = item;
        showStylePanel(item);
      });

      // 鼠标拖拽
      item.addEventListener('mousedown', startDrag);
      // 触摸拖拽
      item.addEventListener('touchstart', startDrag, { passive: true });

      // 内容修改时更新预览
      item.addEventListener('input', updateHtmlPreview);
    }

    // 显示样式面板
    function showStylePanel(item) {
      const rect = item.getBoundingClientRect();
      const viewportWidth = window.innerWidth;
      
      // 计算面板位置，避免超出视口
      let left = rect.left + window.scrollX;
      if (left + 240 > viewportWidth) {
        left = Math.max(0, viewportWidth - 240);
      }
      
      panel.style.top = (rect.bottom + window.scrollY + 5) + 'px';
      panel.style.left = left + 'px';
      panel.classList.add('active');
      
      // 初始化面板值
      document.getElementById('fontSize').value = item.style.fontSize || '14px';
      document.getElementById('fontColor').value = item.style.color || '#333333';
      document.getElementById('fontFamily').value = item.style.fontFamily || 'sans-serif';
      document.getElementById('width').value = item.style.width || '100%';
      document.getElementById('height').value = item.style.height || '';
    }

    // 开始拖拽
    function startDrag(e) {
      currentItem = e.target.closest('.editable-item');
      if (!currentItem) return;
      
      // 防止拖拽时触发文本编辑
      currentItem.contentEditable = "false";
      
      isDragging = true;
      currentItem.classList.add('dragging');
      
      // 记录初始位置和索引
      const clientPos = e.type === 'touchstart'? e.touches[0] : e;
      const rect = currentItem.getBoundingClientRect();
      
      startY = clientPos.clientY;
      startX = clientPos.clientX;
      initialPosition = {
        top: rect.top - window.scrollY,
        left: rect.left - window.scrollX
      };
      
      // 记录原始索引
      const items = Array.from(container.children);
      originalIndex = items.indexOf(currentItem);
      
      // 添加事件监听
      document.addEventListener('mousemove', dragMove);
      document.addEventListener('touchmove', dragMove, { passive: false });
      document.addEventListener('mouseup', endDrag);
      document.addEventListener('touchend', endDrag);
    }

    // 拖拽中
    function dragMove(e) {
      if (!isDragging ||!currentItem) return;
      e.preventDefault();
      
      const clientPos = e.type === 'touchmove'? e.touches[0] : e;
      const deltaY = clientPos.clientY - startY;
      const deltaX = clientPos.clientX - startX;
      
      // 实时更新拖拽元素位置
      currentItem.style.top = (initialPosition.top + deltaY) + 'px';
      currentItem.style.left = (initialPosition.left + deltaX) + 'px';
      
      // 计算当前元素中心点
      const currentRect = currentItem.getBoundingClientRect();
      const currentCenterY = currentRect.top + currentRect.height / 2;
      
      // 获取所有同级元素
      const siblings = Array.from(container.children).filter(item => 
        item!== currentItem && item.classList.contains('editable-item')
      );
      
      // 检查是否需要交换位置
      siblings.forEach(sibling => {
        const siblingRect = sibling.getBoundingClientRect();
        const siblingCenterY = siblingRect.top + siblingRect.height / 2;
        
        // 获取当前元素和兄弟元素在容器中的索引
        const currentIndex = Array.from(container.children).indexOf(currentItem);
        const siblingIndex = Array.from(container.children).indexOf(sibling);
        
        // 当前元素在兄弟元素上方，且移动到兄弟元素下方
        if (currentCenterY > siblingCenterY && currentIndex < siblingIndex) {
          container.insertBefore(currentItem, sibling.nextSibling);
          updateHtmlPreview(); // 更新HTML预览
        }
        // 当前元素在兄弟元素下方，且移动到兄弟元素上方
        else if (currentCenterY < siblingCenterY && currentIndex > siblingIndex) {
          container.insertBefore(currentItem, sibling);
          updateHtmlPreview(); // 更新HTML预览
        }
      });
    }

    // 结束拖拽
    function endDrag() {
      if (!currentItem) return;
      
      isDragging = false;
      currentItem.classList.remove('dragging');
      
      // 重置定位样式，让元素回到正常文档流
      currentItem.style.position = '';
      currentItem.style.top = '';
      currentItem.style.left = '';
      currentItem.style.width = '';
      
      // 重新启用文本编辑
      currentItem.contentEditable = "true";
      
      // 移除事件监听
      document.removeEventListener('mousemove', dragMove);
      document.removeEventListener('touchmove', dragMove);
      document.removeEventListener('mouseup', endDrag);
      document.removeEventListener('touchend', endDrag);
      
      // 最终更新一次HTML预览
      updateHtmlPreview();
    }

    // 应用样式
    function applyStyle() {
      if (!currentItem) return;
      
      currentItem.style.fontSize = document.getElementById('fontSize').value;
      currentItem.style.color = document.getElementById('fontColor').value;
      currentItem.style.fontFamily = document.getElementById('fontFamily').value;
      
      const width = document.getElementById('width').value;
      currentItem.style.width = width? width : '';
      
      const height = document.getElementById('height').value;
      currentItem.style.height = height? height + 'px' : '';
      
      closePanel();
      updateHtmlPreview();
    }

    // 关闭面板
    function closePanel() {
      panel.classList.remove('active');
    }

    // 添加新元素
    function addNewItem() {
      const newItem = document.createElement('div');
      newItem.className = 'editable-item';
      newItem.textContent = `新元素 ${container.children.length + 1}`;
      container.appendChild(newItem);
      bindItemEvents(newItem);
      updateHtmlPreview();
    }

    // 更新HTML预览
    function updateHtmlPreview() {
      // 显示容器内的HTML结构
      htmlPreview.textContent = container.innerHTML;
    }

    // 保存当前HTML
    function saveHtml() {
      const htmlContent = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>编辑后的页面</title>
</head>
<body>
  <div class="editable-container">
    ${container.innerHTML}
  </div>
</body>
</html>`;
      
      const blob = new Blob([htmlContent], { type: 'text/html' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'edited-page.html';
      a.click();
      URL.revokeObjectURL(url);
    }

    // 添加保存按钮
    const saveButton = document.createElement('button');
    saveButton.textContent = '保存HTML';
    saveButton.style.marginTop = '10px';
    saveButton.style.padding = '8px 16px';
    saveButton.style.backgroundColor = '#2196F3';
    saveButton.style.color = 'white';
    saveButton.style.border = 'none';
    saveButton.style.borderRadius = '4px';
    saveButton.style.cursor = 'pointer';
    saveButton.onclick = saveHtml;
    document.body.insertBefore(saveButton, document.querySelector('.debug-area'));

    // 添加新元素按钮
    const addButton = document.createElement('button');
    addButton.textContent = '添加新元素';
    addButton.style.marginTop = '10px';
    addButton.style.marginLeft = '10px';
    addButton.style.padding = '8px 16px';
    addButton.style.backgroundColor = '#f1f1f1';
    addButton.style.border = 'none';
    addButton.style.borderRadius = '4px';
    addButton.style.cursor = 'pointer';
    addButton.onclick = addNewItem;
    document.body.insertBefore(addButton, document.querySelector('.debug-area'));

    // 页面加载完成后初始化
    window.addEventListener('DOMContentLoaded', init);
  </script>
</body>
</html>
